/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package daos;

import entitys.Campeonato;
import entitys.Time;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import utils.JpaUtils;

/**
 *
 * @author thiago
 */
public class TimeDAO {
    
      public void persistir(Time time){
    
        if (time.getId()== null){
            this.insert(time);
        }else{
            this.update(time);
        }
    }
    
    public void insert(Time time) {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            manager.getTransaction().begin();
            manager.persist(time);
            manager.getTransaction().commit();
        } catch (Exception e) {
            manager.getTransaction().rollback();
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
      
      
    public void update(Time time) {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            manager.getTransaction().begin();
            manager.merge(time);
            manager.getTransaction().commit();
        } catch (Exception e) {
            manager.getTransaction().rollback();
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
            
    public void delete(Time time) {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            manager.getTransaction().begin();
            time = manager.merge(time);
            manager.remove(time);
            manager.getTransaction().commit();
        } catch (Exception e) {
            manager.getTransaction().rollback();
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
    
    public Time findById(Long id) {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            return manager.find(Time.class, id);
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
    
    public List<Time> listAll() {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            Query query = manager.createQuery("select c from Time c", Time.class);
            return query.getResultList();
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
}
